package cn.lger.controller;

import cn.lger.pojo.*;
import cn.lger.service.ArticleService;
import cn.lger.service.CommentService;
import cn.lger.service.ContactService;
import cn.lger.service.UserService;
import cn.lger.util.FileUploadUtil;
import cn.lger.util.StringEmptyUtil;
import cn.lger.util.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * Code that Changed the World
 *
 * @author Pro
 * @date 2018-06-16.
 */
@RestController
@RequestMapping("api/user")
@Api(tags = "用户控制器")
public class UserController {

    @Value("${upload.path}")
    private String uploadPath;
    @Resource
    private ArticleService articleService;
    @Resource
    private ContactService contactService;
    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;

    @GetMapping("article/list")
    @ApiOperation(httpMethod = "GET", value = "查询所有本用户文章")
    @ApiResponse(code = 200, message = "成功", response = Page.class)
    public Page<Article> getArticles(@ApiParam("当前页，默认0") Integer currentPage,
                                     @ApiParam("一页大小，默认3") Integer size,
                                     @ApiParam("种类，可为null") Integer categoryId,
                                     @ApiIgnore HttpSession session) {
        User user = getSessionUser(session);
        return articleService.findOnePage(currentPage, size, categoryId, user.getId());
    }

    @PostMapping("article")
    @ApiOperation(httpMethod = "POST", value = "上传或更新影评文章，id不空为更新，否则反之")
    @ApiResponse(code = 200, message = "成功操作返回Article对象", response = Article.class)
    public Article postArticle(@ApiParam("文章实体类，id为空插入操作，不空更新操作") Article article,
                               @ApiParam("文章图片文件")
                               @RequestParam(value = "file", required = false) MultipartFile file,
                               @ApiIgnore HttpSession session) {
        String imageUrl = FileUploadUtil.uploadFileToFolder(file, uploadPath, "file");
        if (imageUrl != null) {
            article.setImage(imageUrl);
        }
        User user = getSessionUser(session);
        article.setTime(new Date());
        article.setUserId(user.getId());
        if (article.getId() != null) {

            if (articleService.updateByUserId(article, user.getId()) > 0) {
                return article;
            }
        }
        if (articleService.insertOne(article) > 0) {
            if (imageUrl == null){
                article.setImage("static/images/pic01.jpg");
            }
            return article;
        }
        return null;
    }

    @DeleteMapping("article/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "删除相应id的文章")
    public int deleteArticle(@ApiIgnore @PathVariable int id, @ApiIgnore HttpSession session) {
        User user = getSessionUser(session);
        return articleService.deleteByUserIdAndArticleId(id, user.getId());
    }


    @PostMapping("contact")
    @ApiOperation(value = "上传反馈", httpMethod = "POST")
    public int postContact(@ApiParam("反馈信息") String content, @ApiParam("联系电话，11位数字组成")
    @RequestParam String phone, @ApiIgnore HttpSession session) {
        User user = getSessionUser(session);
        Contact contact = new Contact();
        if (StringEmptyUtil.notEmpty(content)) {
            contact.setContent(content);
        } else {
            throw new IllegalArgumentException("内容不能为空");
        }
        if (ValidateUtil.isValidPhoneNumber(phone)) {
            contact.setPhone(phone);
        } else {
            throw new IllegalArgumentException("联系电话不符合要求，请输入11位数字");
        }
        contact.setUsername(user.getUsername());
        return contactService.insertOne(contact);
    }

    @PostMapping("comment")
    @ApiOperation(value = "上传影评评论", httpMethod = "POST")
    public int postComment(@ApiParam(value = "评论内容", required = true) @NonNull String content,
                           @ApiParam(value = "评论文章id", required = true) int articleId,
                           @ApiIgnore HttpSession session) {
        User user = getSessionUser(session);
        Comment comment = new Comment();
        comment.setArticleId(articleId);
        comment.setContent(content);
        comment.setUsername(user.getUsername());
        return commentService.insertOne(comment);
    }

    @PostMapping("upload")
    @ApiOperation(value = "上传文件", httpMethod = "POST")
    public String upload(@RequestParam(value = "file", required = false)
                         @ApiParam("上传时文件名") MultipartFile file) {
        StringBuilder builder = new StringBuilder();
        String url;
        try{
            url = FileUploadUtil.uploadFileToFolder(file, uploadPath, "file");
            builder.append("{\"success\":1,\"message\":\"文件上传成功\",\"url\":\"");
            builder.append(url);
            builder.append("\"}");
        }catch (Exception e){
            builder.append("{\"success\":0,\"message\":\"文件上传失败，请重试\"}");
        }
        return builder.toString();
    }

    @PutMapping
    @ApiOperation(value = "修改用户信息", httpMethod = "PUT")
    public User putUser(@ApiParam("邮箱") String email,
                        @ApiParam("密码") String password,
                        @ApiIgnore HttpSession session) {
        User sessionUser = getSessionUser(session);
        User user = new User();
        user.setUsername(sessionUser.getUsername());
        user.setId(sessionUser.getId());
        user.setPassword(password);
        if (StringEmptyUtil.notEmpty(email)) {
            if (ValidateUtil.isValidEmail(email)) {
                user.setEmail(email);
            }else {
                throw new IllegalArgumentException("邮箱格式不正确");
            }
        } else {
            user.setEmail(sessionUser.getEmail());
        }
        if (userService.update(user) != 0) {
            session.setAttribute("user", user);
        }
        return user;
    }


    @GetMapping("check")
    @ApiOperation(value = "检查该用户名是否存在", httpMethod = "GET")
    public int checkUsername(@ApiParam(value = "用户名", required = true) @RequestParam String username) {
        return userService.checkUsername(username);
    }

    private User getSessionUser(HttpSession session) {
        Object o = session.getAttribute("user");
        User user;
        if (o instanceof User) {
            user = (User) o;
        } else {
            throw new IllegalStateException("用户未登录，请登录后访问");
        }
        return user;
    }

}
